package cn.kent.netty.base.eventLoop;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;

/**
 * {@link io.netty.util.concurrent.DefaultPromise} 使用
 */
@Slf4j
public class TestNettyPromise {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 1. 准备EventLoop对象
        EventLoop eventLoop = new NioEventLoopGroup().next();

        // 2. 可以主动创建 promise 对象, 结果对象
        DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 3. 任意一个线程执行计算,计算完毕后向 promise 填充结果
                log.debug("开始计算");
                try {
                    int i = 1/0;
                    Thread.sleep(1000);
                    promise.setSuccess(80);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    promise.setFailure(e);
                }
            }
        }).start();

        log.debug("等待结果...");
        log.debug("结果是{}", promise.get());
    }
}
